package com.example.dao;


import com.example.Bean.NewsBean;
import com.example.util.DBConnection;


import java.util.Date;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class newsdao {
    DBConnection DBCoon = new DBConnection();
    // todo 后期添加分页功能
    public List<NewsBean> getlist(){
        String sql = "select * from news";
        Connection conn = DBCoon.getConn();
        List<NewsBean> list = new ArrayList<NewsBean>();

        list = null;
        try {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                NewsBean newsBean = new NewsBean();
                newsBean.setNewsID(rs.getInt("NewsID"));
                newsBean.setNewsTitle(rs.getNString("NewsTitle"));
                newsBean.setNewsContent(rs.getString("NewsContent"));
                newsBean.setNewsTime(rs.getString("NewsTime"));
                newsBean.setAdminName(rs.getString("AdminName"));
                list.add(newsBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加新闻
     * @param news
     * @return
     */
    public int add(NewsBean news){
        Connection conn = DBCoon.getConn();
        String sql = "update news set NewsTitle=?,NewsContent=?,NewsTime=?,AdminName=? where NewsID=?";
        try{
            PreparedStatement ps = conn.prepareStatement(sql);
            PreparedStatement pmst=conn.prepareStatement(sql);
            pmst.setString(1,news.getNewsTitle());
            pmst.setString(2,news.getNewsContent());
            pmst.setString(3,(new Date()).toString());
            pmst.setString(4,news.getAdminName());
            pmst.setInt(5,news.getNewsID());
            return pmst.executeUpdate(sql);//执行添加 返回受影响的行数
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }

    public int delete(int newsId){
        Connection conn = DBCoon.getConn();
        try {
            String sql = "delete from news where NewsID=?";
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setInt(1,newsId);
            return pmst.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }
}
